/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "MeshProcess.h"

#include <D3D11.h>

#include "../Components/Camera.h"

#include "../Components/PointLight.h"
#include "../Components/DirectionalLight.h"

#include "../Components/MeshRenderer.h"
#include "../Content/MeshFilter.h"

#include "../Content/VertexShader.h"
#include "../Content/GeometryShader.h"
#include "../Content/PixelShader.h"
#include "../Content/HullShader.h"
#include "../Content/DomainShader.h"

#include "../Content/RasterizerState.h"
#include "../Content/BlendState.h"
#include "../Content/SamplerState.h"
#include "../Content/DepthStencilState.h"

#include "../HLSLCPPDeclarations/ConstantBuffers.fx"

#include "../Managers/DX11Manager.h"
#include "../Directors/DX11Director.h"



namespace Hogshead
{
	namespace DX11Rendering
	{
		ProcessCPP(Hogshead::DX11Rendering::MeshProcess)

		MeshProcess::MeshProcess(void) : _prev_vertex_shader(NULL), _prev_pixel_shader(NULL), _prev_geometry_shader(NULL),
		_prev_hull_shader(NULL), _prev_domain_shader(NULL),
		_prev_rasterizer_state(NULL), _prev_blend_state(NULL), _prev_sampler_state(NULL),
		_world_view_projection_buffer(NULL)
		{
		}


		MeshProcess::~MeshProcess(void)
		{
			if( _world_view_projection_buffer )
				_world_view_projection_buffer->Release();
		}

		void MeshProcess::render(Camera* in_active_camera, HashSet<void*>* in_nonculled_components)
		{
			//clear out all our knowledge about the state of things on the card
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_hull_shader = NULL;
			_prev_domain_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;
			_prev_depth_stencil_state = NULL;


			//setup the viewport
			D3D11_VIEWPORT viewport;
			viewport.Width = (FLOAT)DX11Manager::getWidth();
			viewport.Height = (FLOAT)DX11Manager::getHeight();
			viewport.MinDepth = 0.0f;
			viewport.MaxDepth = 1.0f;
			viewport.TopLeftX = 0;
			viewport.TopLeftY = 0;
			DX11Manager::setViewport( &viewport );

			//this line is a direct port,
			DX11Manager::setDepthStencilState(true, D3D11_DEPTH_WRITE_MASK_ALL, D3D11_COMPARISON_LESS);

			//we assume everything going through this process has the same constant buffer
			//layout at register 0, namely world, view, projection

			//update view,projection from active camera
			if( in_active_camera )
			{
				_world_view_projection._view = in_active_camera->getView();
				_world_view_projection._projection = in_active_camera->getProjection();
				_world_view_projection._camera_position_ws = Vector4(in_active_camera->getParentGameObject()->getTransform().getWorldPosition(), 1.0f);
			}
			else
			{
				error("you will need a camera");
			}

			//iterate through each mesh renderer and do all the stuff needed to draw it
			//this is the only class we know how to send to the card. The extendability
			//of this is in MeshRenderer's design not this process'.
			MeshRenderer* mesh;
			const Technique* current_draw_tech;
			Pass* current_pass;

			for( int i = 0; i < _registered_components.size(); i++ )
			{
				mesh = _registered_components[i]->as<MeshRenderer>();

				//if this object isn't in view of the camera, we don't care about it so continue
				if(!mesh->_never_cull && !in_nonculled_components->contains(_registered_components[i]) && _culling)
					continue;
				
				current_draw_tech = mesh->getTechnique(this->_handle);				

				//do each pass in the technique
				for(int j = 0; j < current_draw_tech->passes().size(); j++)
				{
					current_pass = current_draw_tech->passes()[j];

					//set topology
					DX11Manager::setTopology(current_pass->topology());			

					//------------------------
					//set the shaders
						// vertex
					if(!_prev_vertex_shader || current_pass->_vs != _prev_vertex_shader)
					{
						//for now just set the layout (check to be more optimal at a later time
						DX11Manager::setInputLayout( current_pass->_vs->_input_layout );
						//set the VS
						DX11Manager::setVertexShader( current_pass->_vs->_vs );
						//save it off as prev
						_prev_vertex_shader = current_pass->_vs;
					}
						//hull
					if(!_prev_hull_shader || current_pass->_hs != _prev_hull_shader )
					{
						if( current_pass->_hs )
						{
							//set the hull shader
							DX11Manager::setHullShader( current_pass->_hs->_hs );
							//save off as previous
							_prev_hull_shader = current_pass->_hs;
						}
						else
						{
							DX11Manager::setHullShader( NULL );
							_prev_hull_shader = NULL;
						}
					}
						//domain
					if(!_prev_domain_shader || current_pass->_ds != _prev_domain_shader )
					{
						if( current_pass->_hs )
						{
							//set the domain shader
							DX11Manager::setDomainShader( current_pass->_ds->_ds );
							//save off as previous
							_prev_domain_shader = current_pass->_ds;
						}
						else
						{
							DX11Manager::setDomainShader( NULL );
							_prev_domain_shader = NULL;
						}
					}
						//geometry
					if(!_prev_geometry_shader || current_pass->_gs != _prev_geometry_shader)
					{
						//check to see if there is a Geometry Shader
						if(current_pass->_gs)
						{
							//set the GS
							DX11Manager::setGeomentryShader( current_pass->_gs->_gs );
							//save it off as prev
							_prev_geometry_shader = current_pass->_gs;
						}
						else
						{
							//set the GS
							DX11Manager::setGeomentryShader( NULL );
							//save it off as prev
							_prev_geometry_shader = NULL;
						}
					}
						//pixel
					if(!_prev_pixel_shader || current_pass->_ps != _prev_pixel_shader)
					{
						if(current_pass->_ps)
						{
							//set the PS
							DX11Manager::setPixelShader( current_pass->_ps->_ps );
							//save it off as prev
							_prev_pixel_shader = current_pass->_ps;
						}
						else
						{
							DX11Manager::setPixelShader(NULL);
							_prev_pixel_shader = NULL;
						}
					}

					//-----------------------
					//set the constant buffers
							
					//do register 0 from here, get world from the component, bind it to all three we currently use
					_world_view_projection._world = mesh->getParentGameObject()->getTransform().getWorldMatrix();
					_world_view_projection._wvp =  _world_view_projection._projection * (_world_view_projection._view *_world_view_projection._world);

					DX11Manager::bindConstantBuffer( &_world_view_projection_buffer, 0, (ShaderBindFlags) (VERTEX_SHADER | HULL_SHADER | DOMAIN_SHADER | GEOMETRY_SHADER | PIXEL_SHADER) );
					DX11Manager::updateSubresource(  _world_view_projection_buffer, &_world_view_projection, 0 );

					////bind lighting to register 1 if it uses lighting
					//if( mesh->useLighting() )
					//{
					DX11Manager::bindConstantBuffer( &DX11Manager::getLightingConstantBuffer() , 1, (ShaderBindFlags) (VERTEX_SHADER | HULL_SHADER | DOMAIN_SHADER | PIXEL_SHADER) );
					_parent->updateSpecularExponent( mesh->_specular_exponent );
					DX11Manager::updateConstantBuffer(DX11Manager::getLightingConstantBuffer(), &_parent->getLighting());
					//}

					//get the rest from the component.
					for( int j = 0; j < mesh->constantBufferGroup().size(); j++ )
					{
						DX11Manager::bindConstantBuffer( mesh->constantBufferGroup().get(j).buffer(),
							mesh->constantBufferGroup().get(j).registerNumber(),
							mesh->constantBufferGroup().get(j).shaderBindFlags() );
					}

					//-----------------------
					//set other card states: blend, samplers, rasterizer
					if(current_pass->_rasterizer_state)
					{
						if(!_prev_rasterizer_state || current_pass->_rasterizer_state != _prev_rasterizer_state )
						{
							_prev_rasterizer_state = current_pass->_rasterizer_state;
							DX11Manager::setRasterizerState(_prev_rasterizer_state->_rasterizer_state);
						}
					}

					if(current_pass->_blend_state)
					{
						if(!_prev_blend_state || current_pass->_blend_state != _prev_blend_state)
						{
							_prev_blend_state = current_pass->_blend_state;
							DX11Manager::setBlendState( _prev_blend_state->_blend_state, NULL, 0xffffffff );
						}
					}

					if(current_pass->_depth_stencil_state)
					{
						if(!_prev_depth_stencil_state || current_pass->_depth_stencil_state != _prev_depth_stencil_state)
						{
							_prev_depth_stencil_state = current_pass->_depth_stencil_state;
							DX11Manager::setDepthStencilState(_prev_depth_stencil_state->_depth_stencil_state);
						}
					}

					for( int j = 0; j < current_pass->_sampler_states.size(); j++ )
						DX11Manager::setSamplers(j, 1, &current_pass->_sampler_states[j]->_sampler_state, current_pass->_sampler_states[j]->shader_flags);


					//if(current_pass->_sampler_state)
					//{
					//	if(!_prev_sampler_state || current_pass->_sampler_state != _prev_sampler_state)
					//	{      
					//		//need to come back to this, currently only supporting a single sampler state
					//		_prev_sampler_state = current_pass->_sampler_state;
					//		DX11Manager::setSamplers(0,1, &_prev_sampler_state->_sampler_state, PS);
					//	}
					//}

					//------------------------
					//finally iterate through each vertex buffer and set the buffer along
					//with the maps(Shader Resource Views)

					//NAIVE for now
					//check if we need to check for a streamoutput
					if(current_pass->useStreamOutput())
					{
						DX11Manager::setSOTargets(mesh->meshFilter()->getStreamOutputTargets().size(), (ID3D11Buffer*const*)mesh->meshFilter()->getStreamOutputTargets());
					}
					else
					{
						ID3D11Buffer* buffer_array[1] = {0};
						DX11Manager::setSOTargets(1, buffer_array);
					}

					//buffer, number of primitives's(tri's), size of vertex
					const Vector<Triplet<ID3D11Buffer*, int, int> >& vertex_buffers = mesh->meshFilter()->_Vertex_Buffer_vector;
					for( int mesh_index = 0; mesh_index < vertex_buffers.size(); mesh_index++ )
					{
						//set the vertex buffer on the card
						DX11Manager::setVertexBuffer(vertex_buffers.get(mesh_index).first, vertex_buffers.get(mesh_index).third);

						//update the shader resources
						//more needs to be set here VIA techniques
						if(mesh->meshFilter()->_shader_resources[DIFFUSE].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[DIFFUSE].size())
								DX11Manager::setPSShaderResource(DIFFUSE, &(mesh->meshFilter()->_shader_resources[DIFFUSE].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setPSShaderResource(DIFFUSE, &(mesh->meshFilter()->_shader_resources[DIFFUSE].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[SPECULAR].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[SPECULAR].size())
								DX11Manager::setPSShaderResource(SPECULAR, &(mesh->meshFilter()->_shader_resources[SPECULAR].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setPSShaderResource(SPECULAR, &(mesh->meshFilter()->_shader_resources[SPECULAR].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[NORMAL].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setPSShaderResource(NORMAL, &(mesh->meshFilter()->_shader_resources[NORMAL].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setPSShaderResource(NORMAL, &(mesh->meshFilter()->_shader_resources[NORMAL].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[TRANSPARENCY].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setPSShaderResource(TRANSPARENCY, &(mesh->meshFilter()->_shader_resources[TRANSPARENCY].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setPSShaderResource(TRANSPARENCY, &(mesh->meshFilter()->_shader_resources[TRANSPARENCY].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[INCANDESCENCE].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setPSShaderResource(INCANDESCENCE, &(mesh->meshFilter()->_shader_resources[INCANDESCENCE].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setPSShaderResource(INCANDESCENCE, &(mesh->meshFilter()->_shader_resources[INCANDESCENCE].get(0))->_shader_resource_view);
						}

						//update the shader resources
						//more needs to be set here VIA techniques
						if(mesh->meshFilter()->_shader_resources[DIFFUSE].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[DIFFUSE].size())
								DX11Manager::setDSShaderResource(DIFFUSE, &(mesh->meshFilter()->_shader_resources[DIFFUSE].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setDSShaderResource(DIFFUSE, &(mesh->meshFilter()->_shader_resources[DIFFUSE].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[SPECULAR].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[SPECULAR].size())
								DX11Manager::setDSShaderResource(SPECULAR, &(mesh->meshFilter()->_shader_resources[SPECULAR].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setDSShaderResource(SPECULAR, &(mesh->meshFilter()->_shader_resources[SPECULAR].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[NORMAL].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setDSShaderResource(NORMAL, &(mesh->meshFilter()->_shader_resources[NORMAL].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setDSShaderResource(NORMAL, &(mesh->meshFilter()->_shader_resources[NORMAL].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[TRANSPARENCY].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setDSShaderResource(TRANSPARENCY, &(mesh->meshFilter()->_shader_resources[TRANSPARENCY].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setDSShaderResource(TRANSPARENCY, &(mesh->meshFilter()->_shader_resources[TRANSPARENCY].get(0))->_shader_resource_view);
						}

						if(mesh->meshFilter()->_shader_resources[INCANDESCENCE].size() > 0)
						{
							if(mesh_index < mesh->meshFilter()->_shader_resources[NORMAL].size())
								DX11Manager::setDSShaderResource(INCANDESCENCE, &(mesh->meshFilter()->_shader_resources[INCANDESCENCE].get(mesh_index))->_shader_resource_view);
							else
								DX11Manager::setDSShaderResource(INCANDESCENCE, &(mesh->meshFilter()->_shader_resources[INCANDESCENCE].get(0))->_shader_resource_view);
						}

						

						//finally draw it !!!
						if(vertex_buffers.get(mesh_index).second >= 0)
							DX11Manager::draw(vertex_buffers.get(mesh_index).second, 0);
						else
							DX11Manager::drawAuto();
						
			
					}	
				}
			}


			
		}

		void MeshProcess::registerComponent( IComponent* in_component )
		{
			//grab all MeshRenderers
			if( in_component->is<MeshRenderer>() )
			{
				_registered_components.add( in_component );
			}
		}

		void MeshProcess::unregisterComponent( IComponent* in_component )
		{
			if(in_component->is<MeshRenderer>())
			{
				//start from the end work forward, odds are this will be called most frequently
				//on objects that get turned on and off so they should be towards the last half
				//of the vector
				for(int i = _registered_components.size()-1; i > -1 ; i--)
				{
					if(in_component == _registered_components[i])
					{
						_registered_components.swap(i, _registered_components.size() - 1);
						_registered_components.removeLast();
						return;
					}
				}
			}
		}

		

		void MeshProcess::initialize()
		{
			//get the projection matrix, the manager needs to hold this differently
			_world_view_projection._projection = Matrix4::createPerspectiveProjection(Math::Pi/4.0f, 16.0f/9.0f, 0.01f, 20000.0f );

			//NULL out refs to previous objects since there were none
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;

	

			//create the one cbuffer that is standard and bind it
			DX11Manager::createConstantBuffer( sizeof( WVP), &_world_view_projection_buffer );
			

			this->_enabled = true;
		}

		void MeshProcess::finalize()
		{
			_registered_components.clear();

			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;


			ZeroMemory( &_world_view_projection, sizeof( WVP ) );
			if( _world_view_projection_buffer )
			{
				_world_view_projection_buffer->Release();
				_world_view_projection_buffer = NULL;
			}
		}


	}
}